﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SachOnlineLibrary.DAL;
using SachOnlineLibrary.Public;
using System.Data;
namespace SachOnlineLibrary.BLL
{
    public class QLPhieuDatHangBLL
    {
        PhieuDatHangDAL dondathangDAL;
        ChiTietDatHangDAL chitietdathangDAL;
        TaiKhoanDAL taikhoanDAL;
        SachDAL sachDAL;
        public QLPhieuDatHangBLL()
        {
            dondathangDAL = new PhieuDatHangDAL();
            chitietdathangDAL = new ChiTietDatHangDAL();
            taikhoanDAL = new TaiKhoanDAL();
            sachDAL = new SachDAL();
        }

        public List<DonDatHang> LietKeTatCaDonDatHang()
        {
            List<DonDatHang> listdondathang = new List<DonDatHang>();
            DataTable dt = new DataTable();
            dt = dondathangDAL.LietKeTatCaDonDatHang();
            foreach (DataRow dr in dt.Rows)
            {
                DonDatHang item = new DonDatHang();
                item.ChuyenDoi(dr);
                TaiKhoan tk = new TaiKhoan();
                tk.ChuyenDoi(taikhoanDAL.LayTaiKhoanTheoID(item.TKID).Rows[0]);
                item.TaiKhoan = tk;
                listdondathang.Add(item);

            }
            return listdondathang;
        }

        public List<ChiTietDatHang> LietKeChiTietDatHang(int maphieu)
        {
            DataTable dt = new DataTable();
            dt = chitietdathangDAL.LietKeChiTietDatHang(maphieu);
            List<ChiTietDatHang> listchitietdathang = new List<ChiTietDatHang>();

            foreach (DataRow dr in dt.Rows)
            {
                ChiTietDatHang item = new ChiTietDatHang();
                item.ChuyenDoi(dr);

                Sach sach = new Sach();
                sach.ChuyenDoi(sachDAL.LietKeSach(item.MaSach).Rows[0]);
                item.Sach = sach;
                listchitietdathang.Add(item);
            }

            return listchitietdathang;
        }

        public bool GiaoHang(int maphieu)
        {
            try
            {
                dondathangDAL.CapNhatDonHang(maphieu, "Đã giao", DateTime.Now);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool TraLaiHang(int maphieu)
        {
            try
            {
                dondathangDAL.CapNhatDonHang(maphieu, "Bị trả lại");
                foreach (ChiTietDatHang ctdh in LietKeChiTietDatHang(maphieu))
                {
                    sachDAL.SuaSach(ctdh.MaSach, ctdh.SoLuong);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
